<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './categorydata';
  import { useMessage } from '/@/hooks/web/useMessage';
  import {
    addProductCategoryApi,
    updateProductCategoryApi,
    getParentProductCategoryTreeApi,
  } from '/@/api/modules/business/product/category';
  export default defineComponent({
    name: 'ProductCategoryModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const rowId = ref();
      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 100,
        baseColProps: { span: 24 },
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });

        isUpdate.value = !!data?.isUpdate;

        const treeData = await getParentProductCategoryTreeApi();
        // for (let item of treeData) {
        //   for (let child of item.children) {
        //     console.log(item.id);
        //     console.log(data.record.pId);
        //     console.log(child.id);
        //     if (child.id === data.record.pId) {
        //       console.log(item.id);
        //       data.record.pId = item.id + ',' + data.record.pId;
        //     }
        //   }
        // }
        if (unref(isUpdate)) {
          rowId.value = data.record.id;
          setFieldsValue({
            ...data.record,
          });
        }

        updateSchema({
          field: 'pId',
          componentProps: { treeData },
        });
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增物资分类' : '编辑物资分类'));
      const { createMessage } = useMessage();
      async function handleSubmit() {
        try {
          const values = await validate();
          values.pId = values.pId.toString();
          setModalProps({ confirmLoading: true });
          // TODO custom api
          !unref(isUpdate)
            ? await addProductCategoryApi({ ...values })
            : await updateProductCategoryApi({ ...values, id: rowId.value });
          !unref(isUpdate)
            ? createMessage.success('新增成功！')
            : createMessage.success('编辑成功！');
          closeModal();
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return { registerModal, registerForm, getTitle, handleSubmit };
    },
  });
</script>
